//
//  ZCDownLoadTool.m
//  VoiceMusic
//
//  Created by dllo on 15/10/24.
//  Copyright © 2015年 zhangdeyu. All rights reserved.
//

#import "ZCDownLoadTool.h"
#import "FileModel.h"
#import <ASIHTTPRequest.h>
#import <ASINetworkQueue.h>

#define SAVEDocument [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"video"]
#define TEMPDocument [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingPathComponent:@"temp"]


@interface ZCDownLoadTool ()<ASIHTTPRequestDelegate,ASIProgressDelegate>

@property (nonatomic, strong) ASINetworkQueue *downloadQueue;
@property (nonatomic, assign)BOOL isGo;
@property (nonatomic, strong, readwrite) NSMutableArray *downloadArr;
@property (nonatomic, strong, readwrite) NSMutableArray *finishArr;
@end


@implementation ZCDownLoadTool
+ (ZCDownLoadTool *)shareDownLoad{
    static ZCDownLoadTool *load;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        load = [[ZCDownLoadTool alloc] init];
    });
    return load;
}

- (void)addDownloadTask:(NSString *)fileName
                 urlStr:(NSString *)url singer:(NSString *)sing{
    [self checkFile];
    if ([self checkFile:url]) {
        
    }
    else
    {
        [self createDownloadRequest:fileName urlStr:url st:sing];
    }


}

- (void) setRequest:(ASIHTTPRequest *)request savePath:(NSString *)savePath TempPath:(NSString *)tempPath{
    
    //获取asi的
    [request setDidReceiveResponseHeadersSelector:@selector(responseHeadersSize:)];
    [request setDidFinishSelector:@selector(finishRequest:)];
    
    //设置保存路径
    request.downloadDestinationPath = savePath;
    
    //设置临时路径
    request.temporaryFileDownloadPath = tempPath;
    
    //开启断点续传
    request.allowResumeForFileDownloads = YES;
    
    //设置request显示详细进度
    request.showAccurateProgress = YES;
    
    //progress代理
    request.downloadProgressDelegate = self;

    //request代理
    request.delegate = self;

}

//创建下载文件
- (void)createDownloadRequest:(NSString *)fileName urlStr:(NSString *)url st:(NSString *)str{
    NSString *savePath = [SAVEDocument stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",fileName]];
    NSString *tempPath = [TEMPDocument stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.download",fileName]];
    
    NSLog(@"%@",TEMPDocument);
    NSLog(@"%@",tempPath);
    
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:url]];
    
    [self setRequest:request savePath:savePath TempPath:tempPath];
    
    /**
     *  需要判断是否已有此文件
     */
    FileModel *model = [[FileModel alloc]init];
    model.fileName = fileName;
    model.targetPath = savePath;
    model.tempPath = tempPath;
    model.fileURL = url;
    model.sing = str;
    
    model.downloadState = WillDownload;
    model.time =[NSString stringWithFormat:@"%f",[[NSDate date] timeIntervalSince1970]];
    [request setUserInfo:@{@"File":model}];
    
    
    //向队列中添加request
    [self.downloadQueue addOperation:request];
    
    if (!self.isGo) {
        [self.downloadQueue go];
        self.isGo = YES;
    }
    
    [self.downloadArr addObject:request];

}

//检查是否存在url
- (BOOL)checkFile:(NSString *)str{
    
    for (ASIHTTPRequest *request in self.downloadArr) {
        FileModel *fileInfo = [request.userInfo objectForKey:@"File"];
        if ([fileInfo.fileURL isEqualToString:str]) {
            return YES;
            break;
        }
    }
    for (ASIHTTPRequest *request in self.finishArr) {
        FileModel *fileInfo = [request.userInfo objectForKey:@"File"];
        if ([fileInfo.fileURL isEqualToString:str]) {
            return YES;
            break;
        }
    }
    return NO;
}
//检查是否存在目标文件夹
-(void)checkFile{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if (![fileManager fileExistsAtPath:SAVEDocument]) {
        [fileManager createDirectoryAtPath:SAVEDocument
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
        
      
        
    }
    if (![fileManager fileExistsAtPath:TEMPDocument]) {
        [fileManager createDirectoryAtPath:TEMPDocument
               withIntermediateDirectories:YES
                                attributes:nil
                                     error:nil];
    }
}
//获取下载文件的大小
- (void)responseHeadersSize:(ASIHTTPRequest *)request
{
    
    if ([[request.responseHeaders valueForKey:@"Content-Length"] isEqualToString:@"0"])  return;
    FileModel *fileInfo = [request.userInfo objectForKey:@"File"];
    fileInfo.isFirstReceived = YES;
    fileInfo.downloadState = Downloading;
    fileInfo.fileSize = [request.responseHeaders valueForKey:@"Content-Length"];
    if ([self.delegate respondsToSelector:@selector(updateFileSize)]) {
        [self.delegate updateFileSize];
    }
    NSLog(@"打印我%@",[request.responseHeaders valueForKey:@"Content-Length"]);
}

- (void)pasueDownloadTask:(FileModel *)fileModel{
    
}
- (void)continueDownloadTask:(FileModel *)fileModel{
    
}
- (void)cancelDownloadTask:(FileModel *)fileModel{
    
}


/**
 *  ASI协议方法
 *
 *  @param request 是哪个request的下载信息
 *  @param bytes   每次获取的字节数
 */
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes{
    
    FileModel *fileInfo = [request.userInfo objectForKey:@"File"];
    if (fileInfo.isFirstReceived) {
        fileInfo.isFirstReceived = NO;
        fileInfo.fileReceivedSize = [NSString stringWithFormat:@"%lld",bytes];
    }
    else{
        fileInfo.fileReceivedSize =[NSString stringWithFormat:@"%lld", fileInfo.fileReceivedSize.longLongValue + bytes];
    }
    if ([self.delegate respondsToSelector:@selector(updateTaskProgress:)]) {
        [self.delegate updateTaskProgress:request];
    }
}

- (void)updateDownloadRequest:(ASIHTTPRequest *)tempRequest{
    
    FileModel *fileInfo = [tempRequest.userInfo objectForKey:@"File"];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:tempRequest.originalURL];
    [self setRequest:request savePath:fileInfo.targetPath TempPath:fileInfo.tempPath];
    [request setUserInfo:@{@"File":fileInfo}];
    
    //向队列中添加request
    [self.downloadQueue addOperation:request];
    
    NSInteger i = 0;
    for (ASIHTTPRequest *request in self.downloadArr) {
        if (tempRequest == request) {
            NSLog(@"我进来了");
            break;
        }
        i ++;
    }
    if (!self.isGo) {
        [self.downloadQueue go];
        self.isGo = YES;
    }
}


//完成下载
- (void)finishRequest:(ASIHTTPRequest *)request{
    
    [self.finishArr addObject:request];
    
    [self.downloadArr removeObject:request];
    if ([self.delegate respondsToSelector:@selector(updateFinishList)]) {
        [self.delegate updateFinishList];
    }
}







-(void)failLoad:(ASIHTTPRequest *)request{
    
    NSLog(@"下载失败");
}
/**
 *  重写Queue的Set方法
 *
 *  @return 返回queue
 */
-(ASINetworkQueue *)downloadQueue
{
    
    if (!_downloadQueue ) {
        _downloadQueue = [[ASINetworkQueue alloc] init];
        
        //代理制空
        [_downloadQueue reset];
        
        _downloadQueue.downloadProgressDelegate = self;
        _downloadQueue.showAccurateProgress = YES;
        _downloadQueue.shouldCancelAllRequestsOnFailure = NO;
        _downloadQueue.maxConcurrentOperationCount = 2;
        
        [_downloadQueue setRequestDidFailSelector:@selector(failLoad:)];
    }
    
    return _downloadQueue;
    
}
- (NSMutableArray *)downloadArr
{
    if (!_downloadArr) {
        _downloadArr = [NSMutableArray array];
    }
    
    return _downloadArr;
    
    
}
- (NSMutableArray *)finishArr
{
    if (!_finishArr) {
        _finishArr = [NSMutableArray array];
    }
    
    return _finishArr;
    
    
    
}

@end
